from flask import Flask, request, jsonify, make_response
import requests
from message_handler import summarize_all_messages, summarize_certain_messages, add_message
from gettoken import GetToken
import threading
from queue import Queue
import time
import schedule
import json
import logging
from datetime import datetime, timedelta
import re

## 以下为POPO的接口

app = Flask(__name__)
message_queue = Queue()

url = 'https://open.popo.netease.com/open-apis/'
suburl = 'sub-config/v1/'
subscribeurl = url + suburl+ "subscribe"

teamposturl = url + 'robot/v1/team'
p2pposturl = url + 'robot/v1/p2p'

# logging.basicConfig(level=logging.DEBUG, filename='app.log', filemode='a',format="%(asctime)s - %(levelname)s - %(message)s")
# console = logging.StreamHandler()
# console.setLevel(logging.INFO)
# logging.getLogger('').addHandler(console)


# 创建一个logger

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

# 创建一个handler，用于写入日志文件
fh = logging.FileHandler('app.log', mode='a')
fh.setLevel(logging.DEBUG)

# 创建一个handler，用于输出到控制台
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

# 定义handler的输出格式
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
fh.setFormatter(formatter)
ch.setFormatter(formatter)

# 给logger添加handler
logger.addHandler(fh)
logger.addHandler(ch)


#token = 'eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxODAwODMiLCJ1aWQiOm51bGwsImNyZWF0ZWQiOjE3MDgxMzk5MDU5MTQsImV4cCI6MTcwODIyNjM2NX0.MNGTZHPJRtMX--Y8sTKsstTIzontXR6yhlbaBdVLpyt-0j9sFunveTsRigktZoJr547CO_bdddJu3CdQXu8Jrg'
token = GetToken()


def is_valid_date(date_string):
    """
    Check if a date string is in the format 'YYYY-MM-DD'.

    Args:
        date_string (str): A string representing a date.

    Returns:
        bool: True if the date string is in the correct format, False otherwise.
    """
    pattern = re.compile(r'^\d{4}-\d{2}-\d{2}$')
    if pattern.match(date_string):
        return True
    else:
        return False
    
        
# 消息的分发
def process_message(msg):
    #过滤自己的消息
    if msg['eventType'] == 'MSG_SEND' and msg['eventData']['from']!='grp.yunxintalkmate@corp.netease.com':
        msg_data = msg['eventData']

        #管理员直接发送给助手的消息
        if msg_data['sessionType'] == 1 and msg_data['from'] in ['hsfn0737@corp.netease.com', 'hzliuxuping@corp.netease.com']:                        
            date_all_process(msg_data['notify'])

            
        #@小泡助手，处理消息
        elif msg_data['sessionType'] == 3 and msg_data['atType'] == 1 and 'grp.yunxintalkmate@corp.netease.com' in msg_data['atList']: 
            my_list = msg_data['notify'].split()
            command = "".join(my_list[1:])
            target_list = [msg_data['sessionId']]
            date_target_process(command,target_list)

        #收到群发消息，加入消息队列
        elif msg_data['sessionType'] == 3: 
            add_message(msg)
        

#录入字符串转换，群成员用
def date_target_process(time,target_list):
        if time == '今天' or time == '':
            date = datetime.now()
            date = date.strftime("%Y-%m-%d")
            post_certain_message(date, target_list)
        elif time == '昨天':
            date = datetime.now() - timedelta(days=1)
            date = date.strftime("%Y-%m-%d")
            post_certain_message(date, target_list)
        elif is_valid_date(time): 
            date = time
            post_certain_message(date, target_list)
        else:
            command = 'uncertain'
            post_certain_message(command, target_list)

#指定日期所有群消息，管理者用
def date_all_process(time):
        if time == '今天':
            date = datetime.now()
            date = date.strftime("%Y-%m-%d")
            post_all_message(date)
        elif time == '昨天':
            date = datetime.now() - timedelta(days=1)
            date = date.strftime("%Y-%m-%d")
            post_all_message(date)
        elif time == '群发':
            date = datetime.now() - timedelta(days=1)
            date = date.strftime("%Y-%m-%d")
            post_all_message_online(date)
        elif is_valid_date(time): 
            date = time
            post_all_message(date)
        else:
            date = datetime.now()
            date = date.strftime("%Y-%m-%d")
            post_all_message(date)

#abble和我的测试群，接受所有消息
testtarget = '4544838'

# 给群推送消息，分别给相应的群推送消息
def post_certain_message(date, target_list):
    sender = 'grp.yunxintalkmate@corp.netease.com'
    use_guide = '你好，我是小宝，你可以在群里@我并加入今天、昨天或者具体日期(2023-06-01), 我就会对指定日期的群消息进行总结哦。https://docs.popo.netease.com/lingxi/133b7720e29345ffaeb508a37c0df1fc'

    if date == 'uncertain':
        for target in target_list:
            teampost(sender, target, use_guide)
    else:
        summaries = summarize_certain_messages(date,target_list)    

        if summaries == '服务出错':
            print('服务出错')
            return
        # 遍历字典的所有项
        for target, summary in summaries.items():
            info = '以下为群:'+target + '于' + date + '的消息总结：\n\n' + summary
            teampost(sender, target, info)

# 指定日期所有群消息发给管理人员
def post_all_message(date):
    summaries = summarize_all_messages(date)
    if summaries == '服务出错':
        print('服务出错')
        return
    
    sender = 'grp.yunxintalkmate@corp.netease.com'

    # 遍历字典的所有项
    for target, summary in summaries.items():
        if summary != '聊天记录太少，不需要总结': #群发时不发聊天记录少的群
            info = '以下为群:'+target + '于' + date + '的消息总结：\n\n' + summary
            time.sleep(1) # 每个循环间隔1秒
            teampost(sender,testtarget,info)

# 指定日期所有群消息发给所有群
def post_all_message_online(date):
    summaries = summarize_all_messages(date)
    sender = 'grp.yunxintalkmate@corp.netease.com'

    # 遍历字典的所有项
    for target, summary in summaries.items():
        if summary != '聊天记录太少，不需要总结': #群发时不发聊天记录少的群
            info = '以下为群:'+target + '于' + date + '的消息总结：\n\n' + summary
            time.sleep(1) # 每个循环间隔1秒
            teampost(sender,target,info)



def schedule_post_message(date):
    summaries = summarize_all_messages(date)
    sender = 'grp.yunxintalkmate@corp.netease.com'

    # 遍历字典的所有项
    for target, summary in summaries.items():
        if summary != '聊天记录太少，不需要总结': #群发时不发聊天记录少的群
            info = '以下为群:'+target + '于' + date + '的消息总结：\n\n' + summary
            time.sleep(1) # 每个循环间隔1秒
            teampost(sender,target,info)
            time.sleep(1) # 每个循环间隔1秒
            teampost(sender,testtarget,info)
            logger.info(f'群定时消息已发送：{target}')

# 消息处理
def worker():
    while True:
        data = message_queue.get()
        if data is None:
            break
        print("开始处理消息: ", data)
        logger.info(f"开始处理消息")
        process_message(data)
        #conclusion = summarize_group_messages()

#发送消息
def teampost(sender,receiver,message):
    # 请求体
    headers = {
        "Open-Access-Token": token,
        "Content-Type": "application/json"
    }
    data = {
        "sender": sender,
        "receiver": receiver, 
        "message": message
    }

    # 发送POST请求
    response = requests.post(teamposturl, headers=headers, data=json.dumps(data))
    
    # 检查响应状态码
    if response.status_code == 200 and response.json()['errcode'] == 0:
        print("发送成功")
        logger.info('发送成功:')
    elif response.status_code == 200 and response.json()['errcode']!= 0:
        print (f"POPO消息发送失败,error code：{response.json()['errcode']}")
        print (f"POPO消息发送原因：{response.json()['errmsg']}")
        logger.info(f"发送失败，状态码：{response.json()['errcode']}")
        logger.info(f"发送失败，状态码：{response.json()['errmsg']}")

    else:
        print(f"发送失败，状态码：{response.status_code}")
        logger.info(f"发送失败，状态码：{response.status_code}")


def updatetoken():
    global token
    logger.info(f'token待更新: {token}')

    # 延迟1秒打印任务运行时间
    #logger.info(f"Next run: {schedule.next_run()}")

    token = GetToken()
    print('token更新成功：', token)
    logger.info(f'token已更新: {token}')
    
    #暂停每日的消息发送
    schedule_post() 

def schedule_post():
    date = datetime.now() - timedelta(days=1)
    date = date.strftime("%Y-%m-%d")
    schedule_post_message(date)

    logger.info('定时消息已发送')

def schedule_tasks():
    schedule.every().day.at("09:25").do(updatetoken)
    #schedule.every(1).hours.do(updatetoken)
    logger.info(f"Next run: {schedule.next_run()}")
    #print("Next run:", schedule.next_run())

    while True:
        schedule.run_pending()
        time.sleep(60) # 每 60 秒检查一次

def start_schedule_tasks():
    thread = threading.Thread(target=schedule_tasks)
    #thread.daemon = True
    thread.start()

@app.route('/callback', methods=['GET', 'POST'])
def callback():
    if request.method == 'POST':
        data = request.json
        # 将消息放入队列
        message_queue.put(data)
        return ""
    else:
        #处理POPO的验证信息，这里没有对签名进行验证
        nonce = request.args.get('nonce')
        print('收到nonce:', nonce)
        if nonce:
            return nonce
        else:
            return "No nonce received.", 400
        
if __name__ == '__main__':
    try:
        worker_thread = threading.Thread(target=worker)
        worker_thread.start()
        start_schedule_tasks()        
        app.run(host="0.0.0.0", port=5000)
        #app.run(port=5000)
    finally:
        # 结束 worker 线程
        message_queue.put(None)
        worker_thread.join()




